import { memo, useEffect, useState } from 'react'
import './index.scss'
import { MyButton, MyInput } from '../../../../components'
import classNames from 'classnames'
import http from '../../../../utils/http'
import api from '../../../../api'
import SparkMD5 from 'spark-md5';
import { message, Upload, type UploadProps } from 'antd'
interface activePlaylistInfoT{
    id:string|number,
    name:string,
    descripe:string,
    coverUrl:string,
}

interface propsT{
    onPlayListWithAll:(id:string|number)=>void,
    activePlaylistInfo:activePlaylistInfoT,
    isEdit:boolean,
    onClose: ()=>void,
    onEdit:(name:string,descripe:string,cover_url?:string)=>void
}



const PlaylistInfo = memo(({onPlayListWithAll,activePlaylistInfo,isEdit,onClose,onEdit}:propsT)=>{
    const [messageApi, contextHolder] = message.useMessage();

    const [infoName,setInfoName] = useState<string>('')
    const [infoDescripe,setInfoDescripe] = useState<string>('')
    const [fileTasks, setFileTasks] = useState<{[key: string]: {progress: number, file: File}}>({});

    function handleClose(){
        onClose()
    }

    function handleSave(){
        onEdit(infoName,infoDescripe)
    }

        // 启动文件上传
    const startFileUpload = async (file: File) => {
        // const taskId = uuidv4(); // 生成唯一任务ID
        const taskId = 6746546513
        const CHUNK_SIZE = 5 * 1024 * 1024;
        
        setFileTasks(prev => ({
            ...prev,
            [taskId]: { file, progress: 0 }
        }));
        
        try {
            // 1. 初始化上传
            const initRes = await http.post(api.file.init_upload, {
                file_name: file.name,
                size: file.size,
                mime_type: file.type,
                total_chunks: Math.ceil(file.size / CHUNK_SIZE),
            });
            
            const serverTaskId = initRes.data.task_id;
            
            // 2. 上传所有分片
            const chunks = createFileChunks(file, CHUNK_SIZE);
            let uploaded = 0;
            
            for (let i = 0; i < chunks.length; i++) {
                const formData = new FormData();
                formData.append('task_id', serverTaskId);
                formData.append('chunk_index', i.toString());
                formData.append('chunk', chunks[i].chunk);
                
                await http.post(api.file.upload_chunk, formData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                });
                
                // 更新进度
                uploaded++;
                const progress = Math.floor((uploaded / chunks.length) * 100);
                setFileTasks(prev => ({
                    ...prev,
                    [taskId]: {...prev[taskId], progress}
                }));
            }
            
            // 3. 完成上传
            const completeRes = await http.post(api.file.complete_upload, {
                task_id: serverTaskId
            });
            
            const fileInfo = completeRes.data;

            console.log(fileInfo);
            onEdit(infoName,infoDescripe,fileInfo.file_url)
        } catch (err) {
            messageApi.error('上传失败: ');
        } finally {
        // 清理任务
            setFileTasks(prev => {
                const newTasks = {...prev};
                delete newTasks[taskId];
                return newTasks;
            });
        }
    };
        // 创建文件分片
    const createFileChunks = (file: File, chunkSize: number) => {
        const chunks = [];
        let start = 0;
        
        while (start < file.size) {
            const end = Math.min(start + chunkSize, file.size);
            const chunk = file.slice(start, end);
            chunks.push({
                index: chunks.length,
                chunk
            });
            start = end;
        }
        
        return chunks;
    };

    const coverProps: UploadProps={
        beforeUpload: (file) => {
            const max_size = 1024 * 1024 * 2
            const arrowType = ['png','jpeg','jpg','webp']
            let isPNG = false
            for(let key of arrowType){
                if(file.type.includes(key)){
                    isPNG = true
                    break
                }
            }
            if (!isPNG) {
                messageApi.error(`${file.name}不是图片文件`);
                return false || Upload.LIST_IGNORE
            }
            
            if(file.size > max_size){
                messageApi.error(`${file.name}文件过大:大于${max_size/1024/1024}MB`);
                return false || Upload.LIST_IGNORE;
            }

            startFileUpload(file)
            return false || Upload.LIST_IGNORE;
        },
    }

    useEffect(()=>{ 
        setInfoDescripe(activePlaylistInfo?.descripe)
        setInfoName(activePlaylistInfo?.name)
    },[isEdit])
    
    return (
        <>
            {contextHolder}
            <div className="playlistInfo_box">
                <div className="playlistInfo_list_header">
                    <div className='playlistInfo_list_header_left'>
                        <div className={classNames("playlistInfo_cover",{'playlistInfo_cover_editing':(isEdit&&activePlaylistInfo.descripe!='网易云音乐')})}>            
                            {activePlaylistInfo?.coverUrl?
                            <img src={activePlaylistInfo.coverUrl} alt="" />:
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" filter="none">
                                
                                <g>
                                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z" fill="rgba(16,16,16,1)"></path>
                                </g>
                            </svg>}
                            <div className='playlistInfo_cover_change'>
                                <Upload {...coverProps}>
                                    更换封面
                                </Upload>
                            </div>
                        </div>
                    </div>
                    {(isEdit&&activePlaylistInfo.descripe!='网易云音乐')?<div className="playlistInfo_section_info_editing">
                        <div className='playlistInfo_section_info_name'>
                            <MyInput value={infoName} onChange={((value:string)=>setInfoName(value))} placeholder={activePlaylistInfo?.name}/>
                        </div>
                        <div className='playlistInfo_section_info_descripe'>
                            <h4>描述:</h4>
                            <div className='playlistInfo_section_info_descripe_inp'>
                                <MyInput value={infoDescripe} onChange={((value:string)=>setInfoDescripe(value))} type='textarea' resize='none'></MyInput>
                            </div>
                        </div>
                        <div className='playlistInfo_section_info_actions'>
                            {isEdit?<>
                                <MyButton 
                                    type='primary' 
                                    onClick={handleSave}
                                >
                                    保存更改
                                </MyButton>
                                <MyButton 
                                    type='guest'
                                    onClick={handleClose}
                                >
                                    取消
                                </MyButton>
                            </>:<MyButton 
                                type='primary' 
                                onClick={()=>onPlayListWithAll(activePlaylistInfo?.id)}
                            >
                                播放
                            </MyButton>}
                        </div>
                    </div>:
                    <div className="playlistInfo_section_info">
                        <div className='playlistInfo_section_info_name'>{activePlaylistInfo?.name}</div>
                        <div className='playlistInfo_section_info_descripe'>
                            <h4>描述:</h4>{activePlaylistInfo?.descripe}
                        </div>
                        <div className='playlistInfo_section_info_actions'>
                            <MyButton 
                                type='primary' 
                                onClick={()=>onPlayListWithAll(activePlaylistInfo?.id)}
                            >
                                播放
                            </MyButton>
                        </div>
                    </div>}
                </div>
            </div>
        </>
    )
})

export default PlaylistInfo